﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace 数据绑定
{
    public class SqlHelper
    {
        private static string constr = "server=LAPTOP-4BDJKOV4;uid = sa; pwd = qazabc ; database=Student_db";

        private SqlConnection con = null;

        public SqlHelper()
        {
            con = new SqlConnection(constr);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public DataTable Get(string sql, SqlParameter[] parms)
        {
            try
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                SqlCommand cmd = new SqlCommand(sql, con);
                if (parms != null)
                {
                    cmd.Parameters.AddRange(parms);
                }

                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                sda.Fill(ds);

                return ds.Tables[0];

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
        /// <summary>
        /// 对是否进行增删改 ， 判断
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public bool Execute(string sql, SqlParameter[] parms)
        {
            try
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                SqlCommand cmd = new SqlCommand(sql, con);
                if (parms != null)
                {
                    cmd.Parameters.AddRange(parms);
                }
                int result = cmd.ExecuteNonQuery();

                return result > 0 ? true : false;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
    }
}